from rest_framework import serializers
from .models import User,Clazz
from datetime import datetime,timedelta


class ClazzSerializer(serializers.ModelSerializer):
    gradute_time=serializers.SerializerMethodField(method_name="get_gradute_time")
    def get_gradute_time(self,obj):
        start:datetime=obj.create_time
        return start.date()+timedelta(days=obj.duration *30)
    class Meta:
        model = Clazz
        fields = '__all__'

class UserSerializer(serializers.ModelSerializer):
    #username 设置为不必传 默认是必传的
    username = serializers.CharField(required=False)

    # clazz = ClazzSerializer()
    class Meta:
        model = User
        # fields=['id','username','first_name','last_name']
        fields="__all__"

    def create(self, validated_data):
        # validated_data.pop('groups')
        # validated_data.pop('user_permissions')
        if not validated_data['is_staff']:
            validated_data['is_active'] = False

        return User.objects.create_user(**validated_data)

    def update(self, instance, validated_data):
        password=validated_data.pop('password', None)
        if password is not None:
            instance.set_password(password)
        return super().update(instance, validated_data)

class  UserExfieldPassword(serializers.ModelSerializer):
    class Meta:
        model = User
        exclude=['password']


class ClazzAndUser(serializers.ModelSerializer):
    users=UserSerializer(read_only=True,many=True)
    class Meta:
        model = Clazz
        fields = '__all__'